package jointpart.assignment2;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import shared.*;

class Searcher2 {
	
	/**
	 * Returns a linked list created from a text file. 
	 * The objects in this linked list has two elements: 
	 * a string and a pointer 
	 * 
	 * @param filename - the name of the text file
	 * @return HTMLlist start (the head of the linked list)
	 * @throws IOException
	 */
	public static HTMLlist readHtmlList (String filename) throws IOException {
        String name;
        HTMLlist startList;
        HTMLlist currentList;
        HTMLlist tempList;

        // Open the file given as argument
        BufferedReader infile = new BufferedReader(new FileReader(filename));

        //Read the first line
        name = infile.readLine(); 
        startList = new HTMLlist (name, null);
        currentList = startList;
        
        // Read the next line
        name = infile.readLine(); 
        
        //Traverse the file word by word
        while (name != null) {    
            tempList = new HTMLlist(name,null);
            
            // Update the linked list
            currentList.next = tempList;
            currentList = tempList;            
            
            // Read the next line
            name = infile.readLine(); 
        }
        
        // Close the file
        infile.close(); 
        
        //Return list
        return startList;
    }
   
    /**
     * getUrls returns a String with all Urls in which a 
     * word appears
     * 
     * @param l - head of HTMLlist to check 
     * @param word - String with word to search for 
     * @return String with list of Urls
     */
    public static String getUrls(HTMLlist l, String word){
    	//String with URLs found
    	String urlsFound = ""; 
    	
    	//temporary string for storing URL
    	String tempUrl = ""; 
    	
    	//Variable to store if a word match has been found
    	boolean match = false; 
    	
    	//Traverse the list
    	while (l != null) {										
            if (l.str.startsWith("*PAGE")) {//If the word is a page		
            	//Set tempUrl to current page
            	tempUrl = l.str.substring(6);
            	
            	//Set match to false
            	match = false;
            	
            } else if (!match && l.str.equalsIgnoreCase(word)){//If the word is found
            	//Add url to urlsFound string
            	urlsFound += tempUrl + "\n"; 
            	
            	//Set match to true
            	match = true;
            }
            
            //Get next list element
            l = l.next;
        }
    	
    	//Return the urls
    	return urlsFound;
    }
    
}